package cn.ilikes.tools.nosql.jpa.envs;

import java.util.Properties;

import org.slf4j.Logger;

import cn.ilikes.tools.logs.Loggerfactory;
import cn.ilikes.tools.nosql.jpa.JPASQLPersistenUnitEnv;
import cn.ilikes.tools.nosql.jpa.JPASQLRunTimeException;
import cn.ilikes.tools.nosql.jpa.JPASQLSystemEnv;
import cn.ilikes.tools.nosql.jpa.configs.JPASQLPersistenceUnitMetadata;
import cn.ilikes.tools.nosql.jpa.configs.envs.JPASQLConfigurationException;
import cn.ilikes.tools.nosql.jpa.configs.envs.pus.PersistenceUnitConfigure;

public class JPASQLPersistenceUnitEnvConfigFactory {

	private String persistenceUnitsName;
	private Properties configs;
	private JPASQLSystemEnv systemEnv;

	private JPASQLPersistenceUnitMetadata persistenceUnitMetadata;

	public JPASQLPersistenceUnitEnvConfigFactory(String persistenceUnitsName, JPASQLSystemEnv systemEnv, Properties configs, JPASQLPersistenceUnitMetadata persistenceUnitMetadata) {
		super();
		this.persistenceUnitsName = persistenceUnitsName;
		this.configs = configs;
		this.systemEnv = systemEnv;
		this.persistenceUnitMetadata = persistenceUnitMetadata;
	}

	private JPASQLPersistenceUnitMetadata getPersistenceUnitMetadata() {
		return persistenceUnitMetadata;
	}

	private Logger logger = Loggerfactory.instance(JPASQLPersistenceUnitEnvConfigFactory.class);

	public JPASQLPersistenUnitEnv create() {

		Loggerfactory.info(logger, "start init persistenceUnitsName " + persistenceUnitsName + "'s JPA SQL  persisten unit  env  ");
		try {
			JPASQLPersistenceUnitMetadata persistenceUnitMetadata = getPersistenceUnitMetadata();

			if (persistenceUnitMetadata == null)
				throw new JPASQLRunTimeException("not find persistence Units Name : " + persistenceUnitsName + " Persistence Unit  Config ! ");

			JPASQLPersistenUnitEnv hbasePersistenUnitEnv = new JPASQLPersistenUnitEnv(persistenceUnitsName, systemEnv);

			hbasePersistenUnitEnv.setPersistenceUnitMetadata(persistenceUnitMetadata);

			PersistenceUnitConfigure configure = new PersistenceUnitConfigure(configs);
			configure.config(persistenceUnitsName, hbasePersistenUnitEnv);

			hbasePersistenUnitEnv.init();

			return hbasePersistenUnitEnv;
		} catch (JPASQLConfigurationException e) {
			Loggerfactory.error(logger, e);
			throw new JPASQLRunTimeException(e);
		}

	}

}
